#!/bin/bash

# Restore thread affinity script
# Usage: ./restore_affinity.sh <process_keyword> <cpu_range>
# Example: ./restore_affinity.sh stress-ng 0-79

if [ $# -ne 2 ]; then
    echo "Usage: $0 <process_keyword> <cpu_range>"
    echo "Example: $0 stress-ng 0-79"
    exit 1
fi

keyword="$1"
cpu_range="$2"

echo "Restoring threads of processes containing keyword '$keyword' to CPU range: $cpu_range"

# Find processes and restore thread affinity
for pid in $(pgrep -f "$keyword"); do
    echo "Processing process PID: $pid"
    
    # Get all threads of the process (including main thread)
    threads=$(ps -T -p "$pid" --no-headers | awk '{print $2}')
    
    for tid in $threads; do
        if taskset -pc "$cpu_range" "$tid" >/dev/null 2>&1; then
            echo "  Restored thread $tid to CPU range: $cpu_range"
        else
            echo "  Failed to restore thread $tid"
        fi
    done
done

echo "Restoration completed" 